﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using eBusiness.Models;

namespace eBusiness.App_DAL
{
    public class GenericRepository<TEntity> where TEntity : class
    {
        internal ebusinessEntities context;
        internal DbSet<TEntity> DbSet;

        public GenericRepository(ebusinessEntities context)
        {
            this.context = context;
            this.DbSet = context.Set<TEntity>();
        }

        public virtual IQueryable<TEntity> Get(
            Expression<Func<TEntity, bool>> getExpression = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderby = null,
            string includeProperties = "",
            int? pageNumber = null, int? pageSize = null,
            ICollection<Expression<Func<TEntity, bool>>> filters = null)
        {
            IQueryable<TEntity> query = DbSet;

            if (getExpression != null)
            {
                query = query.Where(getExpression);
            }

            if (filters != null && filters.Count > 0)
            {
                foreach (var filter in filters)
                {
                    query = query.Where(filter);
                }
            }

            foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderby != null)
            {
                query = orderby(query);

                if (pageNumber != null && pageSize != null)
                {
                    return query.Skip((pageNumber.Value - 1) * pageSize.Value).Take(pageSize.Value);
                }
            }
            //return query;

            return query;
        }

        public virtual TEntity GetByID(object id)
        {
            return DbSet.Find(id);
        }

        public virtual TEntity Insert(TEntity entity)
        {
            return DbSet.Add(entity);
        }

        public virtual void Update(TEntity entity)
        {
            DbSet.Attach(entity);
            context.Entry(entity).State = EntityState.Modified;
        }
    }
}